package cn.edu.mju.user.config;



import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import cn.edu.mju.common.entity.result.AppHttpCodeEnum;
import cn.edu.mju.common.entity.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 16423
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {


    private final RedisTemplate<String,Object> redisTemplate;

    @Autowired
    public ResourceServerConfig(RedisTemplate<String, Object> redisTemplate) {

        this.redisTemplate = redisTemplate;
    }


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore());

    }

    @Bean
    public TokenStore tokenStore(){
        return new JwtTokenStore(jwtAccessTokenConverter());
    }
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey("123");
        return jwtAccessTokenConverter;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
                .antMatchers(
                        "/vip/updateVip",
                        "/vip/addVipInfo",
                        "/vip/getVipLevel",
                        "/user/updateUserPwd",
                        "/user/uploadAvatar",
                        "/user/logicRemove",
                        "/user/physicallyRemove",
                        "/user/getAllUser",
                        "/user/register",
                        "/user/getUserInfo"

                        ).permitAll()
                .anyRequest().authenticated().and().csrf().disable()
                .addFilterBefore(new OncePerRequestFilter() {
                    @Override
                    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
                        String fullToken = request.getHeader("Authorization");
                        if (fullToken == null){
                            filterChain.doFilter(request,response);
                            return;
                        }
                        System.out.println(fullToken);

                        //分离Bearer 与 jwt数据
                        String authorization = fullToken.split(" ")[1];

                        String flag = (String) redisTemplate.opsForValue().get(authorization);

                        //判断redis中有jwt
                        if (ObjectUtil.isNotEmpty(flag)){
                            //是否有效
                            if ("true".equals(flag)){
                                filterChain.doFilter(request,response);
                                return;
                            }
                        }
                        response.setContentType("application/json;charset=UTF-8");
                        response.getWriter().println(JSONObject.toJSONString(ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN)));
                    }
                }, UsernamePasswordAuthenticationFilter.class);
    }


}
